<?php

/*
 *	Framework namespace
 */
namespace Nano
{
	/*
	 *	Template class
	 *
	 *	@extends	\Kernel
	 */
	class Template extends \Kernel
	{
		/*
		 *	$template	string	Active template
		 */
		public $template = 'default';
		
		/*
		 *	$list	array	List of template folders
		 */
		public $list = array
		(
			'templates_folder' => 'templates',
			'tpl_folder' => 'templates',
			'images_folder' => 'images',
			'stylesheet_folder' => 'css',
			'javascript_folder' => 'js'
		);
		
		/*
		 *	$extension	string	Default template extension
		 */
		public $extension = '.tpl';
		
		/*
		 *	$varsigns	array	Open/Close variables tags
		 */
		public $varsigns = array('{', '}');
		
		/*
		 *	$path	string	Absolute path to template
		 */
		public $path;
		
		/*
		 *	$file	string	Last opend file
		 */
		public $file;
		
		/*
		 *	$contents	array	Array with files contents
		 */
		public $contents = array();
		
		/*
		 *	$content	string	Last used file content
		 */
		public $content;
		
		/*
		 *	Constructor
		 */
		public function __construct()
		{
			$this->path = APPLICATION.DS.$this->list['templates_folder'].DS.$this->template;
			
			$this->check();
		}
		
		/*
		 *	Check for template path
		 *
		 *	@throw
		 */
		public function check()
		{
			if(!Filesystem::is('dir', $this->path))
			{
				throw new \Exception(__CLASS__.': Template folder does not exists');
			}
			
			if(!Filesystem::is('readable', $this->path))
			{
				throw new \Exception(__CLASS__.': Template folder is not readable');
			}
		}
		
		/*
		 *	Open template file
		 *
		 *	@param	string	Relative path to template without extension
		 *	@return	string	File contents
		 *
		 *	@throw
		 */
		public function open($file)
		{
			$this->file = DS.$this->path.DS.$this->list['tpl_folder'].DS.$file.$this->extension;
			
			if(key_exists($this->file, $this->contents))
			{
				return $this->content = $this->contents[$this->file];
			}
			
			if(!Filesystem::is('file', $this->file))
			{
				throw new \Exception(__CLASS__.': Could not open template file "'.$this->file.'"');
			}
			
			return $this->content = $this->contents[$this->file] = Filesystem::get($this->file);
		}
		
		/*
		 *	Replace array keys with array vars
		 *
		 *	@param	array
		 */
		public function parse($array)
		{
			foreach($array as $key => $value)
			{
				$data[$this->varsigns[0].$key.$this->varsigns[1]] = (string)$value;
			}
			
			unset($array);
			
			return str_replace(array_keys($data), array_values($data), $this->content);
		}
	}
}